package cn.sgy.infrastructure.file.autoconfig;

import cn.sgy.infrastructure.file.properties.FileStoreProperties;
import cn.sgy.infrastructure.file.strategy.FileStore;
import cn.sgy.infrastructure.file.strategy.impl.OssFileStore;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author sgy
 * @description 自动配置类
 * @date 2023-11-17
 */
@Configuration
@EnableConfigurationProperties({FileStoreProperties.class})
public class FileAutoConfiguration {

    /**
     * OssClient
     */
    @Bean
    @ConditionalOnClass(OSSClient.class)
    @ConditionalOnProperty(prefix = "infrastructure.file", name = "type", havingValue = "ALI", matchIfMissing = true)
    public OSS oss(FileStoreProperties fileStoreProperties) {
        FileStoreProperties.OssProperties ossProperties = fileStoreProperties.getOss();
        String accessKeyId = ossProperties.getAccessKeyId();
        String accessKeySecret = ossProperties.getAccessKeySecret();
        return new OSSClient(ossProperties.getEndpoint(), new DefaultCredentialProvider(accessKeyId, accessKeySecret), null);
    }

    /**
     * Oss的FileStore
     */
    @Bean
    @ConditionalOnClass(OSSClient.class)
    @ConditionalOnProperty(prefix = "infrastructure.file", name = "type", havingValue = "ALI", matchIfMissing = true)
    public FileStore fileStore(OSS oss, FileStoreProperties fileStoreProperties) {
        return new OssFileStore(oss, fileStoreProperties);
    }

}
